/**
 * jims
 */
package com.jims.master.modules.doctor.web;

import com.jims.master.common.data.StringData;
import com.jims.master.common.utils.StringUtils;
import com.jims.master.common.web.BaseController;
import com.jims.master.modules.doctor.dao.ClinicMasterDao;
import com.jims.master.modules.doctor.entity.ClinicMaster;
import com.jims.master.modules.doctor.entity.ClinicOrders;
import com.jims.master.modules.doctor.entity.PrescriptionApply;
import com.jims.master.modules.doctor.entity.PrescriptionItem;
import com.jims.master.modules.doctor.service.ClinicMasterService;
import com.jims.master.modules.doctor.service.ClinicOrdersService;
import com.jims.master.modules.doctor.service.PrescriptionApplyService;
import com.jims.master.modules.doctor.service.PrescriptionItemService;
import com.jims.master.modules.doctor.vo.PrescDrugVo;
import com.jims.master.modules.sys.entity.Dict;
import com.jims.master.modules.sys.entity.PerformFreqDict;
import com.jims.master.modules.sys.entity.SysOrgDict;
import com.jims.master.modules.sys.entity.User;
import com.jims.master.modules.sys.utils.DictUtils;
import com.jims.master.modules.sys.utils.PerformFreqUtils;
import com.jims.master.modules.sys.utils.SysOrgDictUtils;
import com.jims.master.modules.sys.utils.UserUtils;
import com.jims.master.modules.utils.PrescItemTreeTable;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 门诊处方明细Controller
 * @author CTQ
 * @version 2017-03-13
 */
@Controller
@RequestMapping(value = "${adminPath}/doctor/prescriptionItem")
public class PrescriptionItemController extends BaseController {

	@Autowired
	private PrescriptionItemService prescriptionItemService;
	@Autowired
	private PrescriptionApplyService prescriptionApplyService;
	@Autowired
	private ClinicOrdersService clinicOrdersService;
	@Autowired
	private ClinicMasterService clinicMasterService;
	@Autowired
	private ClinicMasterDao clinicMasterDao;
	
	@ModelAttribute
	public PrescriptionItem get(@RequestParam(required=false) String id) {
		PrescriptionItem entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = prescriptionItemService.get(id);
		}
		if (entity == null){
			entity = new PrescriptionItem();
		}
		return entity;
	}
	
	@RequiresPermissions("user")
	@RequestMapping(value = {"index", ""})
	public String list(PrescriptionItem prescriptionItem,String inoroutFlag,Model model) {
		if (StringUtils.isNotBlank(prescriptionItem.getApplyId())){
			PrescriptionApply apply = prescriptionApplyService.get(prescriptionItem.getApplyId());
			model.addAttribute("apply",apply);
		}
		List<PrescriptionItem> list = prescriptionItemService.findList(prescriptionItem);
		List<PrescriptionItem> treeList=new PrescItemTreeTable(list).buildTree();
		if(treeList.size()==0){
			treeList=list;
		}
		model.addAttribute("itemList", treeList);
		if("0".equals(inoroutFlag)){
			return "modules/doctor/prescription/prescWesternItemIndex";
		} else if("1".equals(inoroutFlag)){
			return "modules/doctor/prescription/in/prescWesternItemIndex";
		} else {
			return "";
		}
	}

	@RequiresPermissions("user")
	@RequestMapping(value = {"listSelect", ""})
	public String listSelect(PrescriptionItem prescriptionItem,String inoroutFlag,Model model) {
		if (StringUtils.isNotBlank(prescriptionItem.getApplyId())){
			PrescriptionApply apply = prescriptionApplyService.get(prescriptionItem.getApplyId());
			model.addAttribute("apply",apply);
		}
		List<PrescriptionItem> list = prescriptionItemService.findList(prescriptionItem);
		List<PrescriptionItem> treeList=new PrescItemTreeTable(list).buildTree();
		if(treeList.size()==0){
			treeList=list;
		}
		model.addAttribute("itemList", treeList);
		if("0".equals(inoroutFlag)){
			return "modules/doctor/prescription/selectHistory/prescSelectHistoryTop";
		} else if("1".equals(inoroutFlag)){
			return "modules/doctor/prescription/in/selectHistory/prescWesternItemIndex";
		} else {
			return "";
		}
	}





	/**
	 * @param prescriptionItem 传递参数
	 * @return String   返回类型
 * @throws
	 * @Title: chineseIndex
	 * @Desription: (中药处方明细列表)
	 * @author CTQ
	 * @date 2017-03-21
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = {"chineseIndex", ""})
	public String chineseIndex(PrescriptionItem prescriptionItem, String inoroutFlag, Model model) {
		List<PrescriptionItem> list = prescriptionItemService.findList(prescriptionItem);
		model.addAttribute("chinaList", list);
		List<SysOrgDict> administrationDicts = SysOrgDictUtils.getSysDictList("ADMINISTRATION_DICT");
		List<SysOrgDict> clinicDict = SysOrgDictUtils.getSysDictList("CLINIC_DICT");
		model.addAttribute("administrationDicts", administrationDicts);
		model.addAttribute("clinicDict", clinicDict);

		List<PerformFreqDict> frequency = PerformFreqUtils.findFreqList();
		model.addAttribute("frequency", frequency);

		List<Dict> specs = DictUtils.getDictList("spec_unit");
		if(list.size()!= 0){
			model.addAttribute("channel", list.get(0).getChannel());
			model.addAttribute("frequency1", list.get(0).getFrequency());
		}
		model.addAttribute("specs", specs);
		model.addAttribute("prescriptionItem", prescriptionItem);
		if("0".equals(inoroutFlag)){
			return "modules/doctor/prescription/prescChineseItemIndex";
		} else {
			return "modules/doctor/prescription/in/prescChineseItemIndex";
		}

	}

	@RequiresPermissions("user")
	@RequestMapping(value = {"chineseIndexSelect", ""})
	public String chineseIndexSelect(PrescriptionItem prescriptionItem, String inoroutFlag, Model model) {
		List<PrescriptionItem> list = prescriptionItemService.findList(prescriptionItem);
		model.addAttribute("chinaList", list);
		List<SysOrgDict> administrationDicts = SysOrgDictUtils.getSysDictList("ADMINISTRATION_DICT");
		model.addAttribute("administrationDicts", administrationDicts);

		List<PerformFreqDict> frequency = PerformFreqUtils.findFreqList();
		model.addAttribute("frequency", frequency);

		List<Dict> specs = DictUtils.getDictList("spec_unit");
		model.addAttribute("specs", specs);
		model.addAttribute("prescriptionItem", prescriptionItem);
		if("0".equals(inoroutFlag)){
			return "modules/doctor/prescription/selectHistory/prescChineseItemIndexSelectHistory";
		} else {
			return "modules/doctor/prescription/in/selectHistory/prescChineseItemIndexSelectHistory";
		}

	}

	@RequiresPermissions("user")
	@RequestMapping(value = "form")
	public String form(PrescriptionItem prescriptionItem,String inoroutFlag, Model model) {
		model.addAttribute("prescriptionItem", prescriptionItem);
		if (StringUtils.isNotBlank(prescriptionItem.getApplyId())){
			PrescriptionApply apply = prescriptionApplyService.get(prescriptionItem.getApplyId());
			model.addAttribute("apply", apply);
		}
		if("0".equals(inoroutFlag)){
			return "modules/doctor/prescription/prescWesternItemForm";
		} else {
			return "modules/doctor/prescription/in/prescWesternItemForm";
		}
	}

	@RequiresPermissions("user")
	@RequestMapping(value = "save")
	@ResponseBody
	public StringData save(PrescriptionItem prescriptionItem) {
	    StringData data=new StringData();
        String id = prescriptionItem.getParent().getId();
        if(StringUtils.isNotBlank(id)){
            PrescriptionItem prescriptionItemDetail = prescriptionItemService.get(id);
            String drugCodeParent = prescriptionItemDetail.getDrugCode();
            String drugCode = prescriptionItem.getDrugCode();
            if(drugCode.equals(drugCodeParent)){
                data.setCode("error");
                data.setData("父子处方药品名称不可相同");
                return data;
            }
        }
        int i=prescriptionItemService.saveWest(prescriptionItem);
		if(i>0){
			data.setCode("success");
			data.setData("保存门诊处方明细成功");
		}else{
			data.setCode("error");
			data.setData("保存门诊处方明细失败");
		}
        return data;
	}

	/**
	 * @param  prescriptionItem 传递参数
	 * @return a    返回类型
 * @throws
	 * @Title: saveChina
	 * @Desription: (保存中药处方)
	 * @author CTQ
	 * @date 2017-03-21
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "saveChina")
	@ResponseBody
	public StringData saveChina(PrescriptionItem prescriptionItem,String isDecoction,String clinicId,String visitId) {
		StringData data=new StringData();
		int i=prescriptionItemService.saveChina(prescriptionItem,isDecoction,clinicId,visitId);
		if(i>0){
			data.setCode("success");
			data.setData("保存门诊中药处方明细成功");
		}else{
			data.setCode("error");
			data.setData("保存门诊中药处方明细失败");
		}
		return data;
	}

	/**
	 * 保存西药处方费用
	 * @param clinicOrders
	 * @return
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "savePrescription")
	@ResponseBody
	public StringData savePrescription(ClinicOrders clinicOrders,String fTreatId,String isTempla,String inoroutFlag,String clinicId) {
		int num =0;
		StringData data=new StringData();
		User user= UserUtils.getUser();

		PrescriptionItem prescriptionItem=new PrescriptionItem();
		prescriptionItem.setApplyId(clinicOrders.getApplyId());
		List<PrescriptionItem> list = prescriptionItemService.getPreItem(prescriptionItem);
		if(list == null){
			data.setCode("error");
			data.setData("请添加药品后保存");
			return data;
		}
		if("0".equals(inoroutFlag)){
			ClinicMaster clinicMaster =clinicMasterService.get(clinicId);
			String doctorId=clinicMaster.getDoctorId();
			clinicMaster.setClinicType("1");
			if(doctorId == null){
				clinicMaster.setDoctorId(user.getId());
			}
			else{
				clinicMaster.setDoctorId(clinicMaster.getDoctorId());
			}
			clinicMaster.setId(clinicId);
			//修改clinic_master挂号状态
			clinicMasterService.updateClinicType(clinicMaster);
			num=clinicOrdersService.savePrescription(clinicOrders,clinicId);
		} else if("1".equals(inoroutFlag)){
 			num = prescriptionApplyService.savePrerscriptitonIn(clinicOrders.getApplyId(),clinicOrders.getOrdersFlag());
		}
		if(num>0){
			data.setCode("success");
			data.setData("保存成功");
		}else{
			data.setCode("error");
			data.setData("保存失败");
		}
		return data;
	}


	@RequiresPermissions("user")
	@RequestMapping(value = "delete")
	@ResponseBody
	public StringData delete(PrescriptionItem prescriptionItem) {
	    StringData data=new StringData();
		int i=prescriptionItemService.delete(prescriptionItem);
        if(i>0){
            data.setCode("success");
            data.setData("删除处方明细成功");
        }else{
            data.setCode("error");
            data.setData("删除处方明细失败");
        }
		return data;
	}

	@RequiresPermissions("user")
	@RequestMapping(value = {"autoComplete", ""})
	@ResponseBody
	public List<PrescDrugVo> autoComplete(String q, String limit, String drugClass, String storageId,String parentId) {
		if(q!=null&&!q.equals("")){
			try {
				q = URLDecoder.decode(q,"UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		 List<PrescDrugVo> PrescDrugVo = prescriptionItemService.findListByParam(q, limit, drugClass, storageId, UserUtils.getOrgId());
        if(StringUtils.isNotBlank(parentId)){
            PrescriptionItem prescriptionItemDetail = prescriptionItemService.get(parentId);
            if(prescriptionItemDetail==null) return PrescDrugVo;
            String drugCodeParent = prescriptionItemDetail.getDrugCode();//子处方去掉父处方药品
            Iterator<PrescDrugVo> listPrescDrugVo = PrescDrugVo.iterator();
            while (listPrescDrugVo.hasNext()) {
                PrescDrugVo prescDrugVo = listPrescDrugVo.next();
                String drugCode = prescDrugVo.getDrugCode();
                if (drugCodeParent.equals(drugCode)) {
                    listPrescDrugVo.remove();
                }
            }
        }
		return PrescDrugVo;
	}

	/**
	 * 门诊处方发药明细
	 * @param prescriptionItem
	 * @param model
	 * @return
	 * @update by CTQ at 2017-07-06 09:24:39
	 */
    @RequiresPermissions("user")
    @RequestMapping(value = {"findByApplyId", ""})
    public String findByApplyId(PrescriptionItem prescriptionItem, Model model) {
        List<PrescriptionItem> prescriptionItemList = prescriptionItemService.findListByApplyId(prescriptionItem);
        model.addAttribute("prescriptionItemList", prescriptionItemList);
		model.addAttribute("prescriptionItem", prescriptionItem);
        return "modules/drugOut/clinicPrescOutForm";
    }

    /**
     * 门诊处方发药明细
     * @param prescriptionItem
     * @param model
     * @return
     * @update by CTQ at 2017-07-06 09:24:39
     */
    @RequiresPermissions("user")
    @RequestMapping(value = {"findInpApplyId", ""})
    public String findInpApplyId(PrescriptionItem prescriptionItem, Model model) {
        List<PrescriptionItem> prescriptionItemList = prescriptionItemService.findListByApplyId(prescriptionItem);
        model.addAttribute("prescriptionItemList", prescriptionItemList);
        model.addAttribute("prescriptionItem", prescriptionItem);
        return "modules/drugOut/inpPrescOutForm";
    }

    /**
     * 手术领药单明细
     * @param prescriptionItem
     * @param model
     * @return
     * @update by CTQ at 2017-07-06 09:24:39
     */
    @RequiresPermissions("user")
    @RequestMapping(value = {"findOperationApplyId", ""})
    public String findOperationApplyId(PrescriptionItem prescriptionItem, Model model) {
        List<PrescriptionItem> prescriptionItemList = prescriptionItemService.findListByApplyId(prescriptionItem);
        model.addAttribute("prescriptionItemList", prescriptionItemList);
        prescriptionItem.updateOrgId();
        model.addAttribute("prescriptionItem", prescriptionItem);
        return "modules/operation/generatePrescriptionForm";
    }

    /**
     * 门诊发药根据applyId查询详情
     * @param prescriptionItem
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequiresPermissions("user")
    @RequestMapping(value = {"drugOutClinicApplyId", ""})
    public String drugOutClinicApplyId(PrescriptionItem prescriptionItem,HttpServletRequest request, HttpServletResponse response, Model model) {
        List<PrescriptionItem> prescriptionItemList = prescriptionItemService.findListByApplyId(prescriptionItem);
        model.addAttribute("prescriptionItemList", prescriptionItemList);
        return "modules/drugOut/drugOutRecordClinicForm";
    }

    /**
     * 门诊发药根据applyId查询详情
     * @param prescriptionItem
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequiresPermissions("user")
    @RequestMapping(value = {"drugInpClinicApplyId", ""})
    public String drugInpClinicApplyId(PrescriptionItem prescriptionItem,HttpServletRequest request, HttpServletResponse response, Model model) {
        List<PrescriptionItem> prescriptionItemList = prescriptionItemService.findListByApplyId(prescriptionItem);
        model.addAttribute("prescriptionItemList", prescriptionItemList);
        return "modules/drugOut/drugInpRecordClinicForm";
    }

	/**
	 *
	 * @param id
	 * @param clinicId
	 * @return
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "saveTreatTemplate")
	@ResponseBody
	public StringData saveTreatTemplate(String id,String fTreatId,String clinicId,String patientId,String prescApplyId,PrescriptionItem prescriptionItem){
		StringData data=new StringData();
		String i=prescriptionItemService.saveTreatTemplate(id,fTreatId,clinicId,patientId,prescApplyId,prescriptionItem.getList());
		if(i!=null){
			data.setCode("success");
			data.setData("保存处方成功");
		}else{
			data.setCode("error");
			data.setData("保存处方失败");
		}
		return data;
	}
	/**
	 *
	 * @return
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "calculatedquantity")
	@ResponseBody
	public StringData calculatedquantity(PrescriptionItem prescriptionItem){
		StringData data=new StringData();
		int i=prescriptionItemService.calculatedquantity(prescriptionItem);
		Map map = new HashMap();
			data.setCode("success");
			map.put("num",i);
			data.setDataMap(map);
		return data;
	}


	@RequiresPermissions("user")
	@RequestMapping(value = "saveChinaTem")
	@ResponseBody
	public StringData saveChinaTem(PrescriptionItem prescriptionItem,String isDecoction,String clinicId,String visitId,String patientId){
		StringData data = new StringData();
		int num = prescriptionItemService.saveChina(prescriptionItem,isDecoction,clinicId,visitId);
		if(num>0){
			data.setCode("success");
			data.setData("保存成功");
		}else{
			data.setCode("error");
			data.setData("保存失败");
		}
		return data;
	}
}